<?php

/* --|   PROFILE
  Software: Socially
  Version: 1.0
  Contact: http://socially.googlecode.com
  Info: http://socially.googlecode.com
  Support: http://socially.googlecode.com
  --------------------------------------------------------------------------
  Author: goker.cebeci | http://gokercebeci.com
  --------------------------------------------------------------------------
  License: Distributed under the GNU General Public License (GPL)
  http://www.gnu.org/licenses/gpl.html
  This program is distributed in the hope that it will be useful - WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE.
  ------------------------------------------------------------------------- */

class profile {

    private static $profile = 'data/profile/';

    private static function _set($a) {
        if (account::update($a)) {
            // PROFILE
            $r = db::query(sprintf("INSERT INTO profile SET ID = %d", $a['ID'])
                            . ($a['homeCountry'] ? sprintf(",homeCountry = '%s'", $a['homeCountry']) : '')
                            . ($a['homeRegion'] ? sprintf(",homeRegion = '%s'", $a['homeRegion']) : '')
                            . ($a['homeLatitude'] ? sprintf(",homeLatitude = '%s'", $a['homeLatitude']) : '')
                            . ($a['homeLongitude'] ? sprintf(",homeLongitude = '%s'", $a['homeLongitude']) : '')
                            . ($a['relationshipStatus'] ? sprintf(",relationshipStatus = '%s'", $a['relationshipStatus']) : '')
                            . (($a['interestedInMen'] || $a['interestedInWomen']) ? sprintf(",interestedIn = '%s'", ($a['interestedInMen'] ? 'men,' : '')
                                            . ($a['interestedInWomen'] ? 'women,' : '')
                                    ) : '')
                            . (($a['lookingForFriendship'] || $a['lookingForDating'] || $a['lookingForRelationship'] || $a['lookingForNetworking']) ? sprintf(",lookingFor = '%s'", ($a['lookingForFriendship'] ? 'friendship,' : '')
                                            . ($a['lookingForDating'] ? 'dating,' : '')
                                            . ($a['lookingForRelationship'] ? 'relationship,' : '')
                                            . ($a['lookingForNetworking'] ? 'networking,' : '')
                                    ) : '')
                            . ($a['highschool'] ? sprintf(",highschool = '%s'", addslashes($a['highschool'])) : '')
                            . ($a['university'] ? sprintf(",university = '%s'", addslashes($a['university'])) : '')
                            . ($a['occupation'] ? sprintf(",occupation = '%s'", addslashes($a['occupation'])) : '')
                            . ($a['companies'] ? sprintf(",companies = '%s'", addslashes($a['companies'])) : '')
                            . ($a['about'] ? sprintf(",about = '%s'", addslashes($a['about'])) : '')
                            . ($a['message'] ? sprintf(",quickMessage = '%s'", addslashes($a['message'])) : '')
                            . ' ON DUPLICATE KEY UPDATE ID=ID'
                            . ($a['homeCountry'] ? sprintf(",homeCountry = '%s'", $a['homeCountry']) : '')
                            . ($a['homeRegion'] ? sprintf(",homeRegion = '%s'", $a['homeRegion']) : '')
                            . ($a['homeLatitude'] ? sprintf(",homeLatitude = '%s'", $a['homeLatitude']) : '')
                            . ($a['homeLongitude'] ? sprintf(",homeLongitude = '%s'", $a['homeLongitude']) : '')
                            . ($a['relationshipStatus'] ? sprintf(",relationshipStatus = '%s'", $a['relationshipStatus']) : '')
                            . (($a['interestedInMen'] || $a['interestedInWomen']) ? sprintf(",interestedIn = '%s'", ($a['interestedInMen'] ? 'men,' : '')
                                            . ($a['interestedInWomen'] ? 'women,' : '')
                                    ) : '')
                            . (($a['lookingForFriendship'] || $a['lookingForDating'] || $a['lookingForRelationship'] || $a['lookingForNetworking']) ? sprintf(",lookingFor = '%s'", ($a['lookingForFriendship'] ? 'friendship,' : '')
                                            . ($a['lookingForDating'] ? 'dating,' : '')
                                            . ($a['lookingForRelationship'] ? 'relationship,' : '')
                                            . ($a['lookingForNetworking'] ? 'networking,' : '')
                                    ) : '')
                            . ($a['highschool'] ? sprintf(",highschool = '%s'", addslashes($a['highschool'])) : '')
                            . ($a['university'] ? sprintf(",university = '%s'", addslashes($a['university'])) : '')
                            . ($a['occupation'] ? sprintf(",occupation = '%s'", addslashes($a['occupation'])) : '')
                            . ($a['companies'] ? sprintf(",companies = '%s'", addslashes($a['companies'])) : '')
                            . ($a['about'] ? sprintf(",about = '%s'", addslashes($a['about'])) : '')
                            . ($a['message'] ? sprintf(",quickMessage = '%s'", addslashes($a['message'])) : '')
                            . ';');
            //.sprintf(" WHERE ID = %d;",$a['ID']));
            if ($r)
                return common::result(600, _('Wrong data request.'));
            cache::del(array("profile[" . $a['ID'] . "]", "profile[" . $a['username'] . "]"));
            return common::result(200, sprintf(_('Your profile has been changed. %s Click here %s to show it!'), '<a href="/profile">', '</a>'));
        }
        //return common::result(200,db::query(sprintf("SELECT ID,access FROM account WHERE ID = '%d';",$a['ID']),true));
    }

    private static function _get(array $a) {
        if ($a['list']) {
            $a['limit'] = $a['limit'] ? ($a['limit'] > 50 ? 50 : $a['limit']) : 10;
            $a['page'] = $a['page'] ? $a['page'] : 1;
            $a['access'] = $a['access'] ? $a['access'] : 1;
            $a['search'] = $a['search'] ? sprintf(" AND (" . (count(explode('@', $a['search'])) > 1 ? "email = '%s'" : "CONCAT(name.' '.lastname) LIKE '%%%s%%'") . ")", $a['search']) : '';
            $d = db::query('SELECT COUNT(ID) as total FROM account WHERE access <= ' . $a['access'] . $a['search'] . ';', true);
            $d->account = db::query('SELECT ID,username,email,name,lastname,sex,birthday,countryCode,regionCode,access FROM account WHERE access <= ' . $a['access']
                            . $a['search']
                            . ' ORDER BY `name` ASC'
                            . ' LIMIT ' . (($a['page'] - 1) * $a['limit']) . "," . $a['limit'] . ';', true, true);
        } else {
            $key = $a['ID'] ? $a['ID'] : $a['username'];
            $d = cache::get("profile[$key]");
            if (!$d) {
                $d = account::get(array('ID' => $a['ID'], 'username' => $a['username']));
                if ($d->ID) {
                    $d->profile = db::query(sprintf("SELECT * FROM profile WHERE ID = %d;", $d->ID), true);
                    // username
                    $d->username = $d->email == $d->username ? '' : $d->username;
                    // profile url
                    $d->url = '/' . ($d->username ? $d->username : LANG . '/profile/' . $d->ID);
                    // get profile photos
                    $d->photo->check = true;
                    $d->photo->mini = self::$profile . $d->ID . '/' . image::name($d->ID . 'mini') . '.jpg';
                    $d->photo->thumb = self::$profile . $d->ID . '/' . image::name($d->ID . 'thumb') . '.jpg';
                    $d->photo->profile = self::$profile . $d->ID . '/' . image::name($d->ID . 'profile') . '.jpg';
                    if (!is_file($d->photo->mini)) {
                        $d->photo->check = false;
                        $d->photo->mini = 'apps/profile/template/images/mini.gif';
                        $d->photo->thumb = 'apps/profile/template/images/thumb.gif';
                        $d->photo->profile = 'apps/profile/template/images/profile.gif';
                    }
                    $d->hometown->country->code = $d->profile->homeCountry ? $d->profile->homeCountry : $d->contact->country->code;
                    $d->hometown->country->name = world::country($d->hometown->country->code, LOCALE);
                    $d->hometown->region->code = $d->profile->homeRegion ? $d->profile->homeRegion : $d->contact->region->code;
                    $d->hometown->region->name = world::region($d->hometown->country->code, $d->hometown->region->code, LOCALE);

                    $d->gender = $d->sex == 'male' ? _('Male') : _('Female');
                    $relationship = array(
                        'single' => _('Single'),
                        'relationship' => _('In a relationship'),
                        'engages' => _('Engaged'),
                        'married' => _('Married'),
                        'complicated' => _('It\'s complicated'),
                        'open-relationship' => _('It\'s complicated'),
                        'windowed' => _('Widowed')
                    );
                    $d->relationshipStatus = $relationship[$d->profile->relationshipStatus];
                    $d->interestedIn->men = preg_match('/^men,/', $d->profile->interestedIn) ? _('Men') : '';
                    $d->interestedIn->women = preg_match('/women,/', $d->profile->interestedIn) ? _('Women') : '';
                    $d->lookingFor->friendship = preg_match('/friendship,/', $d->profile->lookingFor) ? _('Friendship') : '';
                    $d->lookingFor->dating = preg_match('/dating,/', $d->profile->lookingFor) ? _('Dating') : '';
                    $d->lookingFor->relationship = preg_match('/relationship,/', $d->profile->lookingFor) ? _('Relationship') : '';
                    $d->lookingFor->networking = preg_match('/networking,/', $d->profile->lookingFor) ? _('Networking') : '';
                    $d->highschool = $d->profile->highschool;
                    $d->university = $d->profile->university;
                    $d->occupation = $d->profile->occupation;
                    $d->companies = $d->profile->companies;
                    $d->about = $d->profile->about;
                    unset($d->profile);
                    cache::set("profile[$key]", $d);
                }
            }
        }
        $d->status = account::status($d->ID);
        $status['online'] = dgettext('profile', 'Online');
        $status['offline'] = dgettext('profile', 'Busy');
        $status['busy'] = dgettext('profile', 'Offline');
        $d->statusmsg = $status[$d->status];
        return $d;
    }

    private static function _del(array $a) {
        db::query(sprintf("DELETE FROM account WHERE ID = %d", $a['ID']));
        return common::result(200, $a);
    }

    /* -----------------------------------------------------------------------
      PUBLIC FUNCTIONS
      ------------------------------------------------------------------------ */

    public static function set(array $a) {
        if ($a['online']) {
            db::query("INSERT INTO accountOnline (ID, sessionID, status, time, date, IP)
				values (" . UID . ",'" . session_id() . "','online','" . @date('U') . "',NOW(),'" . $_SERVER['REMOTE_ADDR'] . "')
				ON DUPLICATE KEY UPDATE sessionID = '" . session_id() . "', status = 'online',  time = '" . @date('U') . "',
				date = NOW(), IP = '" . $_SERVER['REMOTE_ADDR'] . "';");
            return true;
        }
    }

    public static function get(array $a) {
        $d = self::_get($a);
        return $d;
    }

    /* -----------------------------------------------------------------------
      SPECIAL FUNCTIONS
      ------------------------------------------------------------------------ */

    /**
     * UPDATE
     *
     * @param array $a
     * @return unknown
     */
    public static function update(array $a) {
        $a['ID'] = UID;
        self::_set($a);
    }

    /**
     * QUICK MESSAGE
     *
     * @param array $a
     * @return boolean
     */
    public static function quickMessage(array $a) {
        $a['ID'] = $a['accountID'];
        return self::_set($a);
    }

    public static function photo($a, $cmd='upload') {
        switch ($cmd) {
            default:
            case 'upload':
                $ext = explode('.', $a['image']['name']);
                $ext = strtolower($ext[count($ext) - 1]);
                if (preg_match('/^(gif|png|jpe?g)$/', $ext)) {
                    $r = db::query(sprintf("SELECT COUNT(ID) as `limit` FROM profilePhotos
                    WHERE accountID = %d;", $a['ID']), true);
                    $limited = true;
                    if (GOLD && PROFILE_PHOTO_LIMIT_GOLD > $r->limit)
                        $limited = false;
                    if (SILVER && PROFILE_PHOTO_LIMIT_SILVER > $r->limit)
                        $limited = false;
                    if (NORM && PROFILE_PHOTO_LIMIT_NORM > $r->limit)
                        $limited = false;
                    if ($limited) {
                        $r = 600;
                    } else {
                        // create profile photo directory
                        @mkdir(self::$profile . $a['ID'] . '/');
                        // add db record and update default photo
                        $caption = $a['caption'] ? strip_tags($a['caption']) : $a['image']['name'];
                        db::query(sprintf("UPDATE profilePhotos SET `isDefault` = 0
                        WHERE accountID = %d AND `isDefault` = 1 LIMIT 1;", $a['ID']));
                        db::query(sprintf("INSERT INTO profilePhotos
                                (accountID, caption, `isDefault`, `uploadDate`)
                                VALUES (%d,'%s',1,NOW());", $a['ID'], $caption));
                        $a['imageID'] = db::insertid();
                        $a['file'] = self::$profile . $a['ID'] . '/tmp.' . ($a['ID'] . @date('U')) . '.' . $ext;
                        if (!self::photo($a, 'resize')) {
                            self::photo($a, 'delete');
                            @unlink($a['file']);
                            $r = 800;
                        }
                        @unlink($a['file']);
                        $r = 200;
                        cache::del(array("profile[" . $a['ID'] . "]", "profile[" . $a['username'] . "]"));
                    }
                } else
                    $r = 800;
                return $r;
                break;
            case 'delete':
                $p = self::photos(array('photo' => true, 'ID' => $a['ID']));
                if ($a['check']) {
                    //notification mail
                    $message = sprintf(_('Our moderation group did not approve your photo.')
                            . '<br/><a href="http://' . DOMAIN . '/profile/photos">http://'
                            . DOMAIN . '/profile/photos</a>');
                    notification::mail(array('application' => 'postie', 'sender' => UID,
                        'recipient' => $p->accountID, 'message' => $message));
                }
                if ($p->isDefault) {
                    @unlink(self::$profile . $p->accountID . '/' . image::name($p->accountID . 'profile') . '.jpg');
                    @unlink(self::$profile . $p->accountID . '/' . image::name($p->accountID . 'thumb') . '.jpg');
                    @unlink(self::$profile . $p->accountID . '/' . image::name($p->accountID . 'mini') . '.jpg');
                    self::photo(array('account' => $p->accountID, 'ID' => $p->ID, 'random' => true), 'profile');
                    @cache::del(array("profile[" . $p->accountID . "]", "profile[" . (account::getusername($p->accountID)) . "]"));
                }
                db::query(sprintf("DELETE FROM profilePhotos WHERE ID = %d AND accountID = %d LIMIT 1", $p->ID, $p->accountID));
                @unlink(self::$profile . $p->accountID . '/' . image::name($p->ID . '-normal') . '.jpg');
                @unlink(self::$profile . $p->accountID . '/' . image::name($p->ID . '-thumb') . '.jpg');
                return common::result(200);
                break;
            case 'resize':
                if (move_uploaded_file($a['image']['tmp_name'], $a['file'])) {
                    $img = new image($a['file']);
                    if (($check = $img->check()) != 200)
                        return common::result($check);
                    $img->resize(self::$profile . $a['ID'] . '/' . image::name($a['imageID'] . '-normal'), 600, 600);
                    $img->resize(self::$profile . $a['ID'] . '/' . image::name($a['imageID'] . '-thumb'), 100, 100, array('compress' => 90));
                    $img->resize(self::$profile . $a['ID'] . '/' . image::name($a['ID'] . 'profile'), 200, 600);
                    $img->resize(self::$profile . $a['ID'] . '/' . image::name($a['ID'] . 'thumb'), 100, 100, array('method' => 'crop', 'position' => 'top', 'compress' => 90));
                    $img->resize(self::$profile . $a['ID'] . '/' . image::name($a['ID'] . 'mini'), 50, 50, array('method' => 'crop', 'position' => 'top', 'compress' => 90));
                    $img->kill();
                    if (is_file(self::$profile . $a['ID'] . '/' . image::name($a['imageID'] . '-normal') . '.jpg'))
                        return true;
                    else
                        return false;
                } else
                    return false;
                break;
            case 'profile':
                if ($a['random'])
                    $r = db::query(sprintf("SELECT * FROM profilePhotos
                        WHERE accountID = %d ID <> %d ORDER BY ID DESC LIMIT 1;", $a['account'], $a['ID']), true);
                else
                    $r = db::query(sprintf("SELECT * FROM profilePhotos
                        WHERE ID = %d LIMIT 1;", $a['ID']), true);
                if ($r->ID) {
                    db::query(sprintf("UPDATE profilePhotos SET `isDefault` = 0
                        WHERE accountID = %d AND isDefault = 1 LIMIT 1;", $a['account']));
                    db::query(sprintf("UPDATE photos SET `isDefault` = 1
                        WHERE accountID = %d AND ID = %d LIMIT 1;", $a['account'], $a['ID']));
                    $img = new image(self::$profile . $r->accountID . '/' . image::name($r->ID . '-normal') . '.jpg');
                    $img->resize(self::$profile . $r->accountID . '/' . image::name($r->accountID . 'profile'), 200, 600);
                    $img->resize(self::$profile . $r->accountID . '/' . image::name($r->accountID . 'thumb'), 100, 100, array('method' => 'crop', 'position' => 'top', 'compress' => 90));
                    $img->resize(self::$profile . $r->accountID . '/' . image::name($r->accountID . 'mini'), 50, 50, array('method' => 'crop', 'position' => 'top', 'compress' => 90));
                    $img->kill();
                }
                break;
            case 'check':
                $r = db::query(sprintf("SELECT ID FROM profilePhotos
                    WHERE accountID = %d AND isDefault = 1 LIMIT 1;", UID), true);
                return $r->ID ? true : false;
                break;
            case 'approve':
                db::query(sprintf("UPDATE profilePhotos SET `checked` = 1 WHERE `ID` = '%d';", $a));
                return common::result(200, _('The photo approved'));
                break;
        }
    }

    public static function photos($a) {
        if ($a['owner']) {
            $r = db::query(sprintf("SELECT accountID FROM profilePhotos
                WHERE ID = %d LIMIT 1;", $a['ID']), true);
            return $r->accountID;
        }
        // show as album
        if ($a['album']) {
            $r = new stdClass();
            $r->account = self::get(array('ID' => $a['accountID']));
            $r->photos = db::query(sprintf("SELECT * FROM profilePhotos
                WHERE accountID = %d ORDER BY ID DESC;", $a['accountID']), true, true);
            if ($r->photos)
                foreach ($r->photos as &$i) {
                    $i->src = self::$profile . $a['accountID'] . '/' . image::name($i->ID . '-thumb') . '.jpg';
                }
        }
        // show a photo
        if ($a['photo']) {
            $r = db::query(sprintf("SELECT * FROM profilePhotos
                        WHERE ID = %d LIMIT 1;", $a['ID']), true);
            $r->photos = db::query(sprintf("SELECT * FROM profilePhotos
                WHERE accountID = %d ORDER BY ID DESC;", $r->accountID), true, true);
            if ($r->accountID)
                $r->account = self::get(array('ID' => $r->accountID));
            if ($r->photos)
                foreach ($r->photos as $k => &$i)
                    if ($i->ID == $a['ID'])
                        $point = $k;
            $count = count($r->photos);
            if ($count) {
                $r->next = $r->photos[(($point + 1) % $count)]->ID;
                $r->prev = $r->photos[(($point == 0 ? $count - 1 : $point - 1) % $count)]->ID;
                $r->src = self::$profile . $r->accountID . '/' . image::name($r->ID . '-normal') . '.jpg';
            }
        }
        if ($a['forcheck']) {
            $r = db::query("SELECT * FROM profilePhotos
                WHERE `checked` = 0 ORDER BY ID DESC, reported DESC LIMIT 1;", true);
            $r->account = self::get(array('ID' => $r->accountID));
            $r->src = self::$profile . $r->accountID . '/' . image::name($r->ID . '-normal') . '.jpg';
        }
        return $r;
    }
    
    public static function lastonlines($a) {
        $r = db::query(sprintf("SELECT ID FROM accountOnline WHERE ID IN (SELECT accountID FROM profilePhotos) ORDER BY `date` DESC LIMIT %d", $a['limit']), true, true);
        foreach ($r as $k => $i) {
            $r[$k] = self::get(array('ID' => $i->ID));
        }
        return $r;
    }

    public static function comment($a=false, $cmd = 'add') {
        switch ($cmd) {
            case 'add':
                $c = comment::post(array('app' => 'profile', 'itemID' => $a['itemID'], 'senderID' => $a['senderID'], 'comment' => $a['comment']));
                if ($c) {
                    $owner = db::query(sprintf("SELECT accountID FROM profilePhotos WHERE ID = %d LIMIT 1;", $a['itemID']), true);
                    $owner = profile::get(array('ID' => $owner->accountID));
                    //$owner->status = profile::status($owner->accountID);
                    $sender = profile::get(array('ID' => $a['senderID']));
                    //if ($owner->status == 'offline') {
                    //notification mail
                    $message = sprintf(_('You have a new comment on your %s photo $s from %s.')
                            , '<a href="http://' . DOMAIN . '/profile/photo/' . $a['itemID'] . '">', '</a>'
                            , '<a href="http://' . DOMAIN . '/' . $sender->link . '">' . $sender->fullname . '</a>');
                    notification::mail(array(
                        'application' => 'profile',
                        'sender' => $sender->ID,
                        'recipient' => $owner->ID,
                        'message' => $message
                    ));
                    //}
                    notification::send(array(
                        'application' => 'profile',
                        'sender' => $sender->ID,
                        'recipient' => $owner->ID,
                        'item' => $a['itemID'],
                        'notification' => 'photocomment'
                    ));

                    return common::result(200, _('Your data has been saved... You are redirecting...'), null, '/profile/photo/' . $a['itemID'], true);
                }
                break;
        }
    }

    public static function notification($ID, $sender, $item = null) {
        $notification = array(
            'photocomment' => sprintf(_('%s commented on your %sphoto%s.')
                    , '<a href="http://' . DOMAIN . $sender->url . '">' . $sender->fullname . '</a>'
                    , '<a href="http://' . DOMAIN . '/photos/photo/' . $item . '">', '</a>')
        );
        return $notification[$ID];
    }

    public static function onlines($a) {
        $r = db::query("SELECT COUNT(ID) as total FROM accountOnline
                WHERE `status` <> 'offline';", true);
        $r->results = db::query("SELECT ID, `time` FROM accountOnline
                WHERE `status` <> 'offline' "
                        . ' ORDER BY `ID` DESC'
                        . (!$a['full'] ? ' LIMIT ' . (($a['page'] - 1) * $a['limit']) . "," . $a['limit'] : '') . ";", true, true);
        $r->app = 'profile';
        foreach ($r->results as &$i) {
            $i = profile::get(array('ID' => $i->ID));
        }
        return $r;
    }

    public static function status($ID) {
        $r = db::query(sprintf("SELECT `status` FROM accountOnline WHERE `ID` = '%d' LIMIT 1;", $ID), true);
        return $r->status;
    }

    public static function search($a) {
        $key = implode(',', $a);
        $r = cache::get("profile[search][$key]");
        if (!$r) {
            $q = sprintf(" AND (CONCAT(name,lastname) LIKE '%%%%%s%%%%' OR username = '%s' OR email = '%s')", $a['q'], $a['q'], $a['q']);
            $r = db::query('SELECT COUNT(ID) as total FROM account WHERE access > 2'
                            . ($a['country'] ? sprintf(" AND country = '%s'", $a['country']) : '')
                            . ($a['region'] ? sprintf(" AND region = '%s'", $a['region']) : '')
                            . $q . ';', true);
            $r->results = db::query('SELECT ID FROM account WHERE access > 2'
                            . ($a['country'] ? sprintf(" AND country = '%s'", $a['country']) : '')
                            . ($a['region'] ? sprintf(" AND region = '%s'", $a['region']) : '')
                            . $q
                            . ' ORDER BY `ID` DESC'
                            . (!$a['full'] ? ' LIMIT ' . (($a['page'] - 1) * $a['limit']) . "," . $a['limit'] : '') . ";", true, true);
            cache::set("profile[search][$key]", $r, 6000);
        }
        $country = world::country($a['country'], LOCALE);
        $region = world::region($a['country'], $a['region'], LOCALE);
        $r->title = $a['q'] ? $a['q'] : sprintf(_('Members in %s'), ($a['region'] ? $region . ' / ' . $country : $country));
        $r->description = sprintf(_('Search results for %s in members'), '<strong>' . $r->title . '</strong>');
        foreach ($r->results as &$i) {
            $i = profile::get(array('ID' => $i->ID));
        }
        return $r;
    }

}

?>